package photostock.model;

import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Collections;
import java.util.Vector;

import javax.imageio.ImageIO;

import photostock.control.ItemCache;

public class Photo extends UserItem {

	private static final long serialVersionUID = 20090501L;
	protected String cacheId;
	
	public static final String ICON = "tn_";
	public static final String VIEW = "mx_";
	public static int ICONSIZE = 80;
	public static int VIEWSIZE = 450;
	private int id;
	private int width;
	private int height;
	
	public Photo(UserItem al, String s) {
		super(al, s);
		neededFields = "id,nom,partagee,validee,nbVisites,nbVotes,creationDate,album,user";
		childrenFields = "";
		children = new Vector<UserItem>();
		if (al.getChildrenItems().size() == 0) id = 0;
		else {
			Collections.sort(al.getChildrenItems(), getIdComparator());
			id = al.getChildrenItems().elementAt(al.getChildrenItems().size()-1).getId()+1;
		}
	}

	public Photo(String user, String album, String s) {
		super(user, album, s);
		neededFields = "id,nom,partagee,validee,nbVisites,nbVotes,creationDate";
		childrenFields = "";
		children = new Vector<UserItem>();
		id = 0;
	}

	
	private boolean initItem() {
		infos = super.initItem(this);
		return infos.exists();
	}

	public boolean init() {
		query = "SELECT * FROM photo WHERE nom='"+getName()+"' AND album='" + getParentItem().getName() + "' AND user='"+getParentItem().getParentItem().getName()+"'";
		return initItem();
	}

	public boolean init(String user, String album) {
		query = "SELECT * FROM photo WHERE nom='"+getName()+"' AND album='" + album + "' AND user='"+ user +"'";
		return initItem();
	}

	public boolean createItem() {
		java.sql.Timestamp ts = new java.sql.Timestamp(new java.util.Date().getTime());
		query = "INSERT INTO photo values("+id+", '" + getName() + "', " + isPartagee() + ", " + isValidee() + ",  " + getNbVisites() + ",  " + getNbVotes() + ", '" + getParentItem().getName() + "', '" + getParentItem().getParentItem().getName() + "', '" + ts.toString().substring(0, 19) + "')";
		return super.recItem(this);
	}

	public boolean update() {
		query = "UPDATE photo SET partagee=" + isPartagee() + ", validee=" + isValidee() + ", nbVisites=" + getNbVisites() + ", nbVotes=" + getNbVotes()+ " WHERE nom='" + getName() + "' AND album= '" + getParentItem().getName() + "' and user='" + getParentItem().getParentItem().getName()+ "'";
		return super.updateItem(this);
	}
	
	public boolean delete() {
		query = "DELETE FROM photo WHERE nom='" + getName() + "' AND album= '" + getParentItem().getName() + "' and user='" + getParentItem().getParentItem().getName()+ "'";
		return super.deleteItem(this);
	}
	
	public boolean initChildrenItems() {
		add(toMin());
		add(toMax());
		return children.size() == 0 ? false : true;
	}
	
	public Photo toMin() {
		if(getName().startsWith(ICON)) return this;
		Photo icon;
		if (!ItemFactory.isCached(ICON + getName().replaceAll(VIEW, "")+getId())) {
			
			icon = new Photo(infos.get("user"),infos.get("album"), ICON + getName().replaceAll(VIEW, ""));
			icon.infos = infos;
			icon.setParent(getParentItem());
			if (!icon.exists()) 
				createImage(icon, Photo.ICONSIZE);
		} else {
			icon = (Photo)ItemFactory.getCached(ICON + getName().replaceAll(VIEW, "")+getId());
			icon.infos = infos;
			icon.setParent(getParentItem());
		}
		return icon;
	}

	public Photo toMax() {
		if(getName().startsWith(VIEW)) return this;
		Photo max;
		if (!ItemFactory.isCached(VIEW + getName().replaceAll(ICON, "")+getId())) {
			max = new Photo(infos.get("user"),infos.get("album"), VIEW + getName().replaceAll(ICON, ""));
			max.infos = infos;
			max.setParent(getParentItem());
			if (!max.exists()) 
				createImage(max, Photo.VIEWSIZE);
		} else {
			max = (Photo)ItemFactory.getCached(VIEW + getName().replaceAll(ICON, "")+getId());
			max.infos = infos;
			max.setParent(getParentItem());
		}
		return max;
	}

	public void createImage(Photo item, int maxSize) {
		try {
			BufferedImage bsrc = ItemFactory.getImage(this);
			double widthCoeff = Math.ceil(bsrc.getWidth() > bsrc.getHeight() ? 
								maxSize : maxSize*bsrc.getWidth()/bsrc.getHeight());
											
			double heightCoeff = Math.ceil(bsrc.getWidth() > bsrc.getHeight() ?
					maxSize*bsrc.getHeight()/bsrc.getWidth(): maxSize);
			
			item.width = (int)widthCoeff;
			item.height = (int)heightCoeff;
			BufferedImage bdest = new BufferedImage((int)widthCoeff, (int)heightCoeff, BufferedImage.TYPE_INT_RGB);
			bdest.createGraphics().drawRenderedImage(bsrc,
			AffineTransform.getScaleInstance(widthCoeff/bsrc.getWidth(),heightCoeff/bsrc.getHeight()));
			
			ImageIO.write(bdest,"JPG",new File(item.getHardPath()));
			ItemCache.getInstance().addToCache(item);
   		} catch (Exception e) {
   			System.out.println(e.getClass().getName() + "***" + e.getMessage() + " - " + item.getName());
   		}   	

	}
	
	public int getWidth() {
		if (this.width == 0) {
			this.width = ItemFactory.getImage(this).getWidth();
			this.height = ItemFactory.getImage(this).getHeight();
		}
		return this.width; 
	}
	
	public int getHeight() {
		if (this.height == 0) {
			this.width = ItemFactory.getImage(this).getWidth();
			this.height = ItemFactory.getImage(this).getHeight();
		}
		return this.height; 
	}

	public void partager() {
		if (null != infos && infos.exists() && null != infos.get("partagee")) infos.set("partagee", new Boolean(true).toString());
	}
	
	public boolean isPartagee() {
		return (null == infos || !infos.exists() || null == infos.get("partagee") ? false : new Boolean(infos.get("partagee")));
	}
	
	public void valider() {
		if (null != infos && infos.exists() && null != infos.get("validee")) infos.set("validee", new Boolean(true).toString());
	}
	
	public boolean isValidee() {
		return (null == infos || !infos.exists() || null == infos.get("validee") ? false : new Boolean(infos.get("validee")));
	}

	public void visiter() {
		if (null != infos && infos.exists() && null != infos.get("nbVisites")) infos.set("nbVisites", new Integer(getNbVisites() + 1).toString());
	}
	
	public int getNbVisites() {
		return (null == infos || !infos.exists() || null == infos.get("nbVisites") ? 0 : Integer.parseInt(infos.get("nbVisites")));
	}

	public void voter() {
		if (null != infos && infos.exists() && null != infos.get("nbVotes")) infos.set("nbVotes", new Integer(getNbVotes() + 1).toString());
	}
	
	public int getNbVotes() {
		return (null == infos || !infos.exists() || null == infos.get("nbVotes") ? 0 : Integer.parseInt(infos.get("nbVotes")));
	}
	
	public int getId() {
		return (null == infos || !infos.exists() || null == infos.get("id") ? id : Integer.parseInt(infos.get("id")));
	}

	public void setId(int id) {
		if (null != infos && infos.exists() && null != infos.get("id")) infos.set("id", new Integer(id).toString());
	}

	public String getCreationDate() {
		return (null == infos || !infos.exists() || null == infos.get("creationDate") ? "" : infos.get("creationDate"));
	}

	public void setCreationDate(String s) {
		if (null != infos && infos.exists() && null != infos.get("creationDate")) infos.set("creationDate", s);
	}
}
